package com.ymy.exceptions;

import com.ymy.utils.ConstantUtil;
import com.ymy.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@Slf4j
@RestControllerAdvice
public class GlobalExceptionRespone {


    /**
     * 全局异常捕获
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Object errorHandler( Exception e) {
        log.error("系统错误 ->",e);
        return Result.faild(ConstantUtil.ResponeCode.SYS_ERROR_CODE,ConstantUtil.ResponeCode.SYS_ERROR);
    }
    /**
     * 全局异常捕获
     * @param e
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    public Object nullPointerException( Exception e) {
        log.error("程序中出现空引用，请检查！ ->",e);
        return Result.faild(ConstantUtil.ResponeCode.NULL_POINTER_EXCEPTION_CODE,ConstantUtil.ResponeCode.NULL_POINTER_EXCEPTION);
    }


    /**
     * 业务层需要自己声明异常的情况
     */
    @ExceptionHandler(MyException.class)
    public Object handleMyTokenExcption(MyException e) {
        log.error("->",e);
        return Result.faild(e.getCode(),e.getMsg());
    }



    /**
     *  校验错误拦截处理
     *
     * @param exception 错误信息集合
     * @return 错误信息
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object validationBodyException(MethodArgumentNotValidException exception){

        BindingResult bindingResult = exception.getBindingResult();
        if (bindingResult.hasErrors()) {

            return Result.faild(ConstantUtil.ResponeCode.INVALID_PARAMETER,bindingResult.getFieldError().getDefaultMessage());
        }
        return Result.faild(ConstantUtil.ResponeCode.SYS_ERROR_CODE);
    }


}
